
swustos.wsl = nil;
-- 初始化状态为1
swustos.ws.ws_status=nil
swustos.ws.ws_cb={}
swustos.ws.ws_init=function ()
    swustos.debug("Start WebSocket")
    swustos.wsl = websocket.createClient()
    swustos.wsl:config({headers={['User-Agent']='swustos'}})
    swustos.wsl:on("connection",function(ws)
        swustos.ws.ws_status=true
        swustos.ws.ws_login()
        if swustos.ws.ws_connect then
            pcall(swustos.ws.ws_connect_cb,{})
        end
    end)
    swustos.wsl:on("receive",function(_,msg,opcode)
        swustos.debug(msg)
        if swustos.ws.ws_receive_cb then
            pcall(swustos.ws.ws_receive_cb,{msg})
        end
        local ok,t = pcall(sjson.decode,msg)
        if ok and t then
            if "userdata" == type(t.i) then
            else
                if "nil" == type(swustos.ws.ws_cb[ t.t .. t.i ]) then
                    if swustos.ws.ws_not_regist_cb then
                        pcall(swustos.ws.ws_not_regist_cb,t)
                    end
                else
                    if t.e and string.len(t.e) > 0 then
-- 服务器响应失败回调
                        pcall(swustos.ws.ws_cb[t.t .. t.i].e,{t.e,t})
                    else
-- 服务器响应成功回调
                        pcall(swustos.ws.ws_cb[t.t .. t.i].s,{t.d,t})
                    end
                end             
            end
        else
            if swustos.ws.ws_decode_error_cb then
                pcall(swustos.ws.ws_decode_error_cb,{msg});
            end;
        end;
    end);
    swustos.wsl:on("close",function(_,status)
        swustos.debug("Closed:",status);
        swustos.wsl=nil;
        setTimeout(swustos.ws.ws_init,3000);
    end);
    swustos.wsl:connect(swustos.ws.ws_url);
end;


ws_send = function (cmd,content,success,error)
    local t = tmr.now();
    local obj={i=cmd,t=t,d=content}
    local ok, json = pcall(sjson.encode, obj)
    if ok then
        swustos.ws.ws_cb[t .. cmd]={s=success,e=error}
        swustos.debug(json)
        swustos.wsl:send(json)
    else
        if swustos.ws.ws_send_cb then
            pcall(swustos.ws.ws_send_cb,{cmd,content})
        end
    end    
end;

ws_login = function()
    swustos.ws.ws_send("login",{wifi=wifi.sta.getconfig(),mac=wifi.sta.getmac(),info=node.chipid()},function()
        swustos.debug("Success Login");
    end,swustos.ws.ws_err);
end;
ws_exec=function()

end;
ws_err=function(err,t)
    swustos.debug("Err: " .. err)
end;
ws_log=function(msg)
    swustos.ws.ws_send("log",{m=msg,t=tmr.time()})
end;
